package com.lightChat.netty.websocket;

import com.lightChat.common.MsgActionEnum;
import com.lightChat.netty.model.ChattingWrap;
import com.lightChat.netty.model.UserChannelMap;
import com.lightChat.service.UsersService;
import com.lightChat.util.JSONUtils;
import com.lightChat.util.SpringUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.springframework.context.ApplicationContext;

/**
 * @author sxt
 * @create 2019-11-13 22:22
 */
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    /**
     * 用来存放每个用户的channel
     */
    public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {

        String msg = textWebSocketFrame.text();
        System.out.println(msg);

        //json字符串转换为聊天封装对象
        ChattingWrap chattingWrap = JSONUtils.json2pojo(msg, ChattingWrap.class);

        Integer action = chattingWrap.getAction();

        if(action == MsgActionEnum.CONNECT.type){
            //第一次建立连接
            //建立用户id与channel之间的联系
            String senderId = chattingWrap.getChattingMsg().getSenderId();//用户id
            Channel channel = channelHandlerContext.channel();//用户channel
            UserChannelMap.put(senderId,channel);//userId与channel关系的建立


        }else  if(action == MsgActionEnum.CHAT.type){
            //1、聊天类型的消息，把聊天记录保存到数据库，同时标记消息的签收状态[未签收]

            //获取ApplicationContext对象
            ApplicationContext applicationContext = SpringUtil.getApplicationContext();
            //获取service对象的方法
            UsersService usersService = (UsersService) applicationContext.getBean("usersService");


            //2、 发送消息
            // 从全局用户Channel关系中获取接受方的channel
            Channel channel = UserChannelMap.get("接收方的userId");


            //通过获取到的chanel来发送消息给对应用户
//            channel.writeAndFlush();


        }else if(action == MsgActionEnum.SIGNED.type){ //进行消息的签收

            //签收消息类型，针对具体的消息进行签收，修改数据库中对应消息的签收状态[已签收]



        }else if(action == MsgActionEnum.KEEPALIVE.type){

            System.out.println("进入了心跳");

        }




//        for(Channel c : channels){
//            c.writeAndFlush(new TextWebSocketFrame("服务器接收到的消息为：" + msg));
//        }

    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        super.handlerRemoved(ctx);
        Channel channel = ctx.channel();
        System.out.println("chanel被移除了，id为"+channel.id());

    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channels.add(channel);
        System.out.println("chanel被加进来了，id为"+channel.id());
    }
}
